package com.bgdCA.auth.interceptor;

import com.bgdCA.auth.entity.LoginUserInfo;
import com.bgdCA.auth.utils.JsonUtils;
import com.bgdCA.auth.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @ClassName Captchainterceptor
 * @Description TODO
 * @Author AlvinZheng
 * @Date 2020/8/4 13:52
 * @Version 1.0
 **/
@Slf4j
@Order(4)
@Component
public class CaptchaInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从request获取json
        String json = RequestUtils.getRequestJsonString(request.getInputStream());
        //存入LoginUserInfo
        LoginUserInfo loginUserInfo = JsonUtils.parse(json, LoginUserInfo.class);
        //获取request中的验证码信息
        String requestCode = loginUserInfo.getCaptcha();
        //获取session中的验证码信息
        HttpSession session = request.getSession();
        String savedCode = (String) session.getAttribute("captcha");

        log.info("request code: " + requestCode + " save code :" + savedCode);

        //无论如何都要去除session中的验证码信息
        if (!StringUtils.isEmpty(savedCode)) {
            session.removeAttribute("captcha");
        }
        //判断验证码
        if (StringUtils.isEmpty(requestCode) || StringUtils.isEmpty(savedCode) || !requestCode.equals(savedCode)) {
            //验证码不正确
            log.info("captcha wrong");
            return false;
        }
        log.info("captcha right");
        //正确

        return true;
    }
}
